package com.gzyj.server.factory.jtt808;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;


import com.gzyj.server.config.LogConfig;
import com.gzyj.server.config.SessionCache;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author lhj
 */
@Service
public class NetWorkSerrvice {

    @Resource(name = "clusterRedisTemplate")
    private RedisTemplate<String, Object> clusterRedisTemplate;
    public void send2Veh(String terminalPhoneNo, ByteBuf byteBuf) {
        ChannelHandlerContext channel = SessionCache.storage.get(terminalPhoneNo);
        if (channel == null) {
            LogConfig.commondErrorLog.error("不存在连接");
        } else {
            Channel c = channel.channel();
            LogConfig.commondLog.info("通道：" + c.isActive() + " " + c.isOpen() + " " + c.isRegistered());
            if (!c.isActive()) {
                LogConfig.commondErrorLog.error(terminalPhoneNo + "已断开连接");
            }
            SessionCache.storage.get(terminalPhoneNo).channel().writeAndFlush(byteBuf);
            LogConfig.commondLog.info(terminalPhoneNo + "发送成功");
        }
    }

    @PostConstruct
    public void init() {
        if(!serverMode.equalsIgnoreCase("808")) return;
        Set<String> keys = clusterRedisTemplate.keys(RedisKey_808Online + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                clusterRedisTemplate.delete(RedisKey_808Online + key);
            }
        }
    }


    @Value("${redis.key.808Online}")
    private String RedisKey_808Online;


    @Value("${jtt-server.mode}")
    private String serverMode;


}
